<template>
   <div>
     <card-container style="margin-top: 16px;padding-bottom: 32px" title="账号绑定" label="账号注册" @listenCardConLabel="() => {this.$router.push('/users/register')}">
       <div class="bind-account-item__wrap">
         <div class="bind-account-item">
           <div class="item__left">
             <div class="avatar">
               <yun-icon name="phone" color="#00AAE6"></yun-icon>
             </div>
             <div class="info">
               <p>手机号</p>
               <h6>{{this.hasOwnProperty('mobile') ? mobile : '未绑定'}}</h6>
             </div>
           </div>

           <div class="item__right" @click="handleChange('手机号')" v-if="!this.hasOwnProperty('mobile')">
             更换
           </div>


         </div>
         <div class="bind-account-item">
           <div class="item__left">
             <div class="avatar">
               <yun-icon name="mail" color="#00AAE6"></yun-icon>
             </div>
             <div class="info">
               <p>邮箱</p>
               <h6>{{this.hasOwnProperty('email') ? email : '未绑定'}}</h6>
             </div>
           </div>

           <div class="item__right" @click="handleChange('邮箱')" v-if="!this.hasOwnProperty('email')">
             绑定
           </div>


         </div>
       </div>
       <div class="bind-account-item__wrap" v-if="false">
         <div class="bind-account-item">
           <div class="item__left">
             <div class="avatar">
               <embed src="../../../assets/svg/wechat.svg" width="20" height="16"
                      type="image/svg+xml"
                      pluginspage="http://www.adobe.com/svg/viewer/install/" />
             </div>
             <div class="info">
               <p>微信号</p>
               <h6>{{wxNumber || '未绑定'}}</h6>
             </div>
           </div>

           <div class="item__right">
             更换
           </div>


         </div>
         <div class="bind-account-item" v-if="false">
           <div class="item__left">
             <div class="avatar">
               <embed src="../../../assets/svg/qq.svg" width="18" height="21"
                      type="image/svg+xml"
                      pluginspage="http://www.adobe.com/svg/viewer/install/" />
             </div>
             <div class="info">
               <p>qq号</p>
               <h6>{{qqNumber || '未绑定'}}</h6>
             </div>
           </div>

           <div class="item__right">
             更换
           </div>


         </div>
       </div>

       <div class="bind-account-item__wrap" v-if="false">
         <div class="bind-account-item">
           <div class="item__left">
             <div class="avatar">
               <embed src="../../../assets/svg/dingding.svg" width="18" height="22"
                      type="image/svg+xml"
                      pluginspage="http://www.adobe.com/svg/viewer/install/" />
             </div>
             <div class="info">
               <p>钉钉</p>
               <h6>未绑定</h6>
             </div>
           </div>

           <div class="item__right">
             更换
           </div>


         </div>
       </div>

     </card-container>
     <card-container style="margin-top: 16px;padding-bottom: 32px" title="账号绑定" v-if="false">
       <div class="bind-account-item__wrap">
         <input type="text" placeholder="请输入密码">
         <input type="text" placeholder="请再次确认密码">
       </div>

       <p class="submit-button">保存</p>
     </card-container>
     <card-container style="margin-top: 16px;padding-bottom: 32px" title="修改登录密码" :label="disabled === 'auto' ? '返回':'修改'" @listenCardConLabel="handleRevise">
       <div class="bind-account-item__wrap">
         <div :title="titleMsg">
           <login-input
             :style="{pointerEvents: disabled, width: '334px'}"
             :error-message="newPasswordMsg"
             placeholder="请输入新的密码"
             input-type="2"
             :type="type"
             autocomplete="new-password"
             v-model="newPassword"
             @handleCheck="handleCheckPassword"
             @cancelCheck="newPasswordMsg = ''"
             @keyup.enter.native="savePassword"
             @handleShowPassword="handleShowPassword"
           ></login-input>
         </div>
         <div :title="titleMsg">
           <login-input
             :style="{pointerEvents: disabled, width: '334px'}"
             v-model="verifyCode2"
             input-type="3"
             placeholder="请输入验证码"
             :error-message="verify2ErrMsg"
             :is-count="isCount"
             @handleCheck="handleCheckVerifyCode('password')"
             @cancelCheck="verify2ErrMsg = ''"
             @sendSms="sendVerifyCode('password')"
             @keyup.enter.native="savePassword"
           ></login-input>
         </div>
       </div>

       <p class="submit-button" @click="savePassword" v-if="disabled === 'auto'">保存</p>
     </card-container>

     <div class="popup-box__wrap" v-if="isShow">
       <div class="popup-box__container">
         <div class="popup-box__main">
           <div class="popup-box-title"><p>{{title}}</p></div>
           <login-input
             v-model="account"
             :placeholder="placeholder"
             :error-message="accountErrMsg"
             @handleCheck="handleCheckAccount"
             @cancelCheck="accountErrMsg = ''"
             @keyup.enter.native="handleChangeAccount"
           ></login-input>
           <login-input
             v-model="verifyCode"
             input-type="3"
             placeholder="请输入验证码"
             :error-message="verifyErrMsg"
             :is-count="isCount"
             @handleCheck="handleCheckVerifyCode"
             @cancelCheck="verifyErrMsg = ''"
             @sendSms="sendVerifyCode"
             @keyup.enter.native="handleChangeAccount"
           ></login-input>
           <div class="popup-box-button">
             <button style="margin-right: 20px" @click="handleChangeAccount">确定</button>
             <button @click="() => {
                Object.assign(this.$data, this.$options.data());
                this.isShow = false
             }">取消</button>
           </div>
         </div>
       </div>
     </div>
   </div>
</template>


<script>
  import CardContainer from '../../../components/pc/cardContainer';
  import LoginInput from "../../../components/pc/loginCard/loginInput";
  import config from '../../../action/config';
  import {checkPhone, checkPassword, checkVerification, checkEmail} from '../../users/checkfrom'

  export default {
    name:'setting',
    components:{
      LoginInput,
      CardContainer
    },
    async asyncData({$axios}) {
      let infoResponse = await $axios.$get(config.api.get.Authentication.authsList);
      console.log(infoResponse);
      let local = infoResponse.data.local;
      let auths = {};
      for(let [key, item] of Object.entries(local)) {
        auths[key] = item.account
      }
      console.log(auths);
      return { ...auths }
    },
    data() {
      return {
        type: 'password',     // 显示密码
        isShow: false,
        title: '绑定手机号',
        verifyCode: '',
        account: '',
        placeholder: '',
        accountErrMsg: '',
        verifyErrMsg: '',
        isCount: false,
        newPassword: '',
        newPasswordMsg: '',
        verifyCode2: '',
        verify2ErrMsg: '',
        disabled: 'none',
        titleMsg: '功能在点击修改后启用'
      }
    },
    methods: {
      // 控制密码显示
      handleShowPassword() {
        this.type = this.type === 'password' ? 'text' : 'password';
      },
      // 点击打开弹窗执行
      handleChange(type) {
        Object.assign(this.$data, this.$options.data());
        this.isShow = true;
        this.title = '绑定'+ type;
        this.placeholder = '请输入' + type;
      },
      handleCheckAccount() {
        if (this.title === '绑定手机号') {
          this.accountErrMsg = checkPhone(this.account);
        } else if (this.title === '绑定邮箱') {
          this.accountErrMsg = checkEmail(this.account);
        }
      },
      handleCheckPassword() {
        this.newPasswordMsg = checkPassword(this.newPassword);
      },
      handleCheckVerifyCode(type = '') {
        if (type === 'password') {
          this.verify2ErrMsg = checkVerification(this.verifyCode2);
        } else {
          this.verifyErrMsg = checkVerification(this.verifyCode);
        }
      },
      // 发送验证码
      sendVerifyCode(type = '') {
        if (type === 'password') {
          if (!this.hasOwnProperty('mobile')) {
            this.$message({
              type: 'warning',
              message: '请先绑定手机号'
            });
            return false
          } else {
            this.isCount = false;
            this.getSms(type);
            this.verify2ErrMsg = '';
            this.isCount = true;
            setTimeout(() => {
              this.isCount = false;
            }, 60000);
            return false
          }
        }
        if (this.title === '绑定手机号') {
          this.isCount = false;
          this.accountErrMsg = checkPhone(this.account);
          if (this.accountErrMsg === '') {
            this.getSms();
            this.verifyErrMsg = '';
            this.isCount = true;
            setTimeout(() => {
              this.isCount = false;
            }, 60000);
          }
        } else if (this.title === '绑定邮箱') {
          this.isCount = false;
          this.accountErrMsg = checkEmail(this.account);
          if (this.accountErrMsg === '') {
            this.getEmail();
            this.verifyErrMsg = '';
            this.isCount = true;
            setTimeout(() => {
              this.isCount = false;
            }, 60000);
          }
        }
      },
      async getSms(type = '') {
        let account = this.account !== '' ? this.account : this.mobile;
        let smsResponse = await this.$axios.$get(config.api.get.Sms.send, {
          params: {
            mobile: account
          }
        });
        if (smsResponse.code === 0) {
          this.$message({
            type: 'success',
            message: '短信发送成功！'
          });
        } else {
          if (type === 'password') {
            this.verify2ErrMsg = smsResponse.msg;
          } else {
            this.verifyErrMsg = smsResponse.msg;
          }
          this.$message({
            type: 'info',
            message: smsResponse.msg
          });
        }
      },
      async getEmail() {
        let emailResponse = await this.$axios.$get(config.api.get.Email.send, {
          params: {
            email: this.account
          }
        });
        if (emailResponse.code === 0) {
          this.$message({
            type: 'success',
            message: '邮件发送成功！'
          });
        } else {
          this.verifyErrMsg = emailResponse.msg;
          this.$message({
            type: 'info',
            message: emailResponse.msg
          });
        }
      },
      async handleChangeAccount() {
        this.handleCheckAccount();
        this.handleCheckVerifyCode();
        if (this.accountErrMsg !== '' || this.verifyErrMsg !== '') return false;
        let changeRes;
        if (this.title === '绑定手机号') {
          changeRes = await this.$axios.$post(config.api.post.User.bindPhone, {},
            {
              params: {
                mobile: this.account,
                verifyCode: this.verifyCode
              }
            });
          if (changeRes.code === 0) {
            this.$message({
              type: 'success',
              message: '绑定手机号成功！'
            });
            this.mobile = this.account;
            this.isShow = false;
            Object.assign(this.$data, this.$options.data());
          } else {
            this.$message({
              type: 'info',
              message: changeRes.msg
            });
          }
        } else if (this.title === '绑定邮箱') {
          changeRes = await this.$axios.$post(config.api.post.User.bindEmail, {},
            {
              params: {
                email: this.account,
                verifyCode: this.verifyCode
              }
            });
          if (changeRes.code === 0) {
            this.$message({
              type: 'success',
              message: '绑定邮箱成功！'
            });
            this.email = this.account;
            this.isShow = false;
            Object.assign(this.$data, this.$options.data());
          } else {
            this.$message({
              type: 'info',
              message: changeRes.msg
            });
          }
        }
      },
      handleRevise() {
        this.disabled = this.disabled === 'auto' ? 'none' : 'auto';
        // 取消时 清空输入框 错误提示
        if (this.disabled === 'none') {
          Object.assign(this.$data, this.$options.data());
        } else {
          this.titleMsg = '';
        }
      },
      async savePassword() {
        this.handleCheckPassword();
        this.verify2ErrMsg = checkVerification(this.verifyCode2);

        if (this.newPasswordMsg !== '' && this.verify2ErrMsg !== '') return false;
        let resetResponse;

        resetResponse = await this.$axios.$put(config.api.put.User.revisePassword, {
          mobile: this.mobile,
          password: this.newPassword,
          verifyCode: this.verifyCode2
        });
        console.log(resetResponse);
        if (resetResponse.code === 0) {
          this.$message({
            type: 'success',
            message: '修改密码成功！'
          });
          Object.assign(this.$data, this.$options.data());
        } else {
          this.verify2ErrMsg = resetResponse.msg;
          this.$message({
            type: 'error',
            message: resetResponse.msg
          });
        }
      }
    },
  }

</script>


<style lang="scss" scoped>

  .bind-account-item__wrap{
    width:726*$length;
    margin:32*$length auto 0;

    @extend %flex-row-spb;

    .bind-account-item{
      width:334*$length;
      height:100*$length;
      background-color: #F4F8FA;
      border-radius: 4*$length;
      box-sizing: border-box;
      padding:24*$length 30*$length;
      @extend %flex-row-spb;
      .item__left{
        @extend %flex-row-spb;

        .avatar{
          width:52*$length;
          height:52*$length;
          background-color: #fff;
          @extend %flex-row-center;
          border-radius: 50%;

        }
        .info{
          @extend %flex-column-center;
          align-items: flex-start;
          margin-left:20*$length;

          p{
            @include fontStyle(14,19,500,#666,left);
          }
          h6{
            margin-top: 9*$length;
            @include fontStyle(14,19,500,#666,left);
          }
        }
      }
      .item__right{
        @extend %cursorPointer;
        @include fontStyle(14,19,500,#55B946,left);
      }




    }
  }

  .submit-button{
    width:148*$length;
    height:48*$length;
    border-radius: 4*$length;
    background-color: #75D098;
    @include fontStyle(14,48,500,#fff,center);
    margin:32*$length auto 0;

    @extend %cursorPointer;
    @extend %animate-transition;
    &:hover{
      filter:brightness(110%);
    }
  }

  .popup-box__wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 8000;
    background-color: rgba(33, 41, 44, 0.4);
    .popup-box__container{
      width: 334*$length;
      padding: 40*$length 40*$length 40*$length 40*$length;
      background-color: #fff;
      @include border-radius(4*$length);
      .popup-box__main{
        .popup-box-title{
          margin-bottom: 40*$length;
          @include fontStyle(20,27,500,#2F2F2F,center)
        }
        .popup-box-button{
          @extend %flex-row-spb;
          justify-content: flex-end;
          > button {
            width: 80*$length;
            background-color: rgba(0, 170, 230, .8);
            border: none;
            cursor: pointer;
            @include border-radius(4*$length);
            @extend %animate-transition;
            @include fontStyle(16,40,500,#fff,center);
            &:hover {
              background-color: rgba(0, 170, 230, 1);
            }
          }
        }
      }
    }
  }
</style>
